package com.sugon.xuanyuan;

import java.io.*;
import java.sql.*;

public class ImageStorage {
    private static final String DB_URL = "jdbc:mysql://100.150.0.123:3306/test";
    private static final String USER = "root";
    private static final String PASS = "admin1234@sugon";

    public static void main(String[] args) {
        String imagePath = "C:\\Users\\admin\\Desktop\\20250808-132800.jpg";
        String imageName = "test2";

        try {
            // 存储图片到数据库
            storeImage(imagePath, imageName);

            // 从数据库读取图片
//            byte[] imageData = retrieveImage(imageName);
//            if (imageData != null) {
//                saveImageToFile(imageData, "retrieved_image.jpg");
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void storeImage(String imagePath, String imageName) throws Exception {
        Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
        PreparedStatement pstmt = conn.prepareStatement("INSERT INTO image (name, image_data) VALUES (?, ?)");

        FileInputStream fis = new FileInputStream(imagePath);
        pstmt.setString(1, imageName);
        pstmt.setBinaryStream(2, fis, (int) new File(imagePath).length());
        pstmt.executeUpdate();


        pstmt.close();
        conn.close();
    }

    private static byte[] retrieveImage(String imageName) throws Exception {
        Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
        PreparedStatement pstmt = conn.prepareStatement("SELECT image_data FROM images WHERE name = ?");
        pstmt.setString(1, imageName);

        ResultSet rs = pstmt.executeQuery();
        byte[] imageData = null;
        if (rs.next()) {
            imageData = rs.getBytes("image_data");
        }

        rs.close();
        pstmt.close();
        conn.close();

        return imageData;
    }

    private static void saveImageToFile(byte[] imageData, String outputImagePath) throws IOException {
        FileOutputStream fos = new FileOutputStream(outputImagePath);
        fos.write(imageData);

    }
}
